package com.mzba.easy.weibo.ui;

import java.io.File;
import java.io.FileInputStream;
import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.text.Html;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.mzba.easy.weibo.BasicActivity;
import com.mzba.easy.weibo.R;
import com.mzba.easy.weibo.db.CommentEntry;
import com.mzba.easy.weibo.db.EmotionField;
import com.mzba.easy.weibo.db.StatusTimelineEntry;
import com.mzba.easy.weibo.util.AppContext;
import com.mzba.easy.weibo.util.BasicUIEvent;
import com.mzba.easy.weibo.util.DateUtil;
import com.mzba.easy.weibo.util.ImageLoader;
import com.mzba.easy.weibo.util.ServiceUtils;
import com.mzba.easy.weibo.util.StringUtil;
import com.mzba.easy.weibo.util.UICore;
import com.mzba.easy.weibo.util.WeiboManager;
import com.mzba.easy.weibo.widget.CustomTextView;
import com.mzba.easy.weibo.widget.RemoteImageView;
/**
 * 
 * @author 06peng
 *
 */
public class StatusTimeLineAdapter extends BaseAdapter implements Callback, BasicUIEvent {
	
	private Context context;
	private List<StatusTimelineEntry> entries;
	private ListView listView;
	private ImageLoader photoLoader;
	
	public static final int DESTROYDIALOG = 0x00000101;
	private static final int comment_status = 0x00000102;
	private static final int comment_status_error = 0x00000103;
	private static final int reply_comment = 0x00000104;
	
	private LayoutParams paramsTop;
	
	private PopupWindow pop;
	
	private WeiboManager weibo;
	private boolean isRetweet = false;
	private Handler handler;
	
	private LinearLayout preLayout;
	private EditText currentEdit;
	private View popViewToShow;
	
	
	public static class ViewHolder {
		RemoteImageView avatarView;
		CustomTextView textView;
		TextView timeView;
		RelativeLayout photoLayout;
		ImageView photoView;
		TextView sourceView;
		Button retweetView;
		Button commentView;
		
		LinearLayout retweetLayout;
		CustomTextView retweetTextView;
		TextView retweetTimeView;
		RelativeLayout retweetPhotoLayout;
		ImageView retweetPhotoView;
		TextView retweetSourceView;
		Button retweetRetweetView;
		Button retweetCommentView;
		
		LinearLayout bodyLayout;
		ImageButton emotionView;
		ImageView commentRetweetView;
		LinearLayout retweetSelectLayout;
		Button commentButtonView;
		EditText editView;
		LinearLayout viewCommentsLayout;
	}
	
	public StatusTimeLineAdapter(Context context, List<StatusTimelineEntry> entries, ListView listView) {
		this.context = context;
		this.entries = entries;
		this.listView = listView;
		photoLoader = new ImageLoader(context, AppContext.FRIENDSTIMELINE_PATH);
		paramsTop = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		paramsTop.topMargin = 15;
		weibo = new WeiboManager(context);
		handler = new Handler(this);
		popViewToShow = LayoutInflater.from(context).inflate(R.layout.status_timeline_item, null);
		initGridView();
	}

	@Override
	public int getCount() {
		return entries.size();
	}

	@Override
	public Object getItem(int arg0) {
		return entries.get(arg0);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	/* (non-Javadoc)
	 * @see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup)
	 */
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder = null;
//		if (convertView == null) {
			convertView = LayoutInflater.from(context).inflate(R.layout.status_timeline_item, null);
			holder = new ViewHolder();
			holder.avatarView = (RemoteImageView) convertView.findViewById(R.id.iv_author_photo);
			holder.textView = (CustomTextView) convertView.findViewById(R.id.status_timeline_text);
			holder.timeView = (TextView) convertView.findViewById(R.id.status_timeline_time);
			holder.photoLayout = (RelativeLayout) convertView.findViewById(R.id.status_timeline_photo_layout);
			holder.photoView = (ImageView) convertView.findViewById(R.id.status_timeline_photo);
			holder.sourceView = (TextView) convertView.findViewById(R.id.status_timeline_from);
			holder.retweetView = (Button) convertView.findViewById(R.id.status_timeline_retweet);
			holder.commentView = (Button) convertView.findViewById(R.id.status_timeline_comment);
			holder.retweetLayout = (LinearLayout) convertView.findViewById(R.id.status_timeline_retweet_layout);
			holder.retweetTextView = (CustomTextView) convertView.findViewById(R.id.status_timeline_retweet_text);
			holder.retweetTimeView = (TextView) convertView.findViewById(R.id.status_timeline_retweet_time);
			holder.retweetPhotoLayout = (RelativeLayout) convertView.findViewById(R.id.status_timeline_retweet_photo_layout);
			holder.retweetPhotoView = (ImageView) convertView.findViewById(R.id.status_timeline_retweet_photo);
			holder.retweetSourceView = (TextView) convertView.findViewById(R.id.status_timeline_retweet_from);
			holder.retweetRetweetView = (Button) convertView.findViewById(R.id.status_timeline_retweet_retweet);
			holder.retweetCommentView = (Button) convertView.findViewById(R.id.status_timeline_retweet_comment);
			holder.bodyLayout = (LinearLayout) convertView.findViewById(R.id.status_timeline_bodylayout);
			holder.bodyLayout.setVisibility(View.GONE);
			
			holder.editView = (EditText) convertView.findViewById(R.id.timeline_comment_edit);
			holder.emotionView = (ImageButton) convertView.findViewById(R.id.timeline_comment_emotion);
			holder.commentRetweetView = (ImageView) convertView.findViewById(R.id.timeline_comment_retweet_select);
			holder.retweetSelectLayout = (LinearLayout) convertView.findViewById(R.id.timeline_comment_retweet_select_layout);
			holder.commentButtonView = (Button) convertView.findViewById(R.id.timeline_comment_comment);
			holder.viewCommentsLayout = (LinearLayout) convertView.findViewById(R.id.comments_timeline_bodylayout);
			convertView.setTag(holder);
//		} else {
//			holder = (ViewHolder) convertView.getTag();
//		}
		try {
			final StatusTimelineEntry entry = entries.get(position);
			if (entry.getUser() != null) {
				holder.avatarView.setDefaultImage(R.drawable.avatar_default_big);
				if (entry.getUser() != null && entry.getUser().getProfile_image_url() != null) {
					holder.avatarView.setImageUrl(entry.getUser().getProfile_image_url(), AppContext.UNAVAILABLE, position, listView);
				}
				holder.avatarView.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(context, UserinfoActivity.class);
						intent.putExtra("userid", entry.getUser().getId());
						context.startActivity(intent);
					}
				});
				String username = entry.getUser().getScreen_name() + ":" + "&nbsp;";
				holder.textView.setText(entry.getText(), username, AppContext.getInstance().getFaceMap());
			}
			holder.timeView.setText(DateUtil.getCreateAt(entry.getCreated_at()));
			if (StringUtil.isNotBlank(entry.getThumbnail_pic())) {
				holder.photoLayout.setVisibility(View.VISIBLE);
				photoLoader.DisplayImage(entry.getThumbnail_pic(), holder.photoView, R.drawable.nophoto);
			} else {
				holder.photoLayout.setVisibility(View.GONE);
			}
			holder.sourceView.setText(Html.fromHtml("来自" + entry.getSource()));
			if (entry.getReposts_count() > 0) {
				holder.retweetView.setText("转发(" + entry.getReposts_count() + ")");
			} else {
				holder.retweetView.setText("转发");
			}
			
			if (entry.getComments_count() > 0) {
				holder.commentView.setText("评论(" + entry.getComments_count() + ")");
				holder.viewCommentsLayout.setVisibility(View.VISIBLE);
				holder.viewCommentsLayout.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(context, CommentsActivity.class);
						intent.putExtra("id", entry.getId());
						context.startActivity(intent);
					}
				});
			} else {
				holder.commentView.setText("评论");
			}
			holder.commentView.setTag(holder.bodyLayout);
			holder.bodyLayout.setTag(holder.editView);
			if (entry.isSeleted()) {
				holder.bodyLayout.setVisibility(View.VISIBLE);
			}
			if (preLayout != null) {
				preLayout.setVisibility(View.GONE);
			}
			holder.commentView.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					if (entry.getComments_count() > 0) {
						String choices[] = new String[] {"评论微博", "查看评论列表"};
						chooseAction(choices, entry.getId());
					} else {
						Intent intent = new Intent(context, NewsActivity.class);
						intent.putExtra("id", entry.getId());
						intent.putExtra(AppContext.NEWTYPE, 3);
						context.startActivity(intent);
					}
//					LinearLayout bodyLayout = (LinearLayout) v.getTag();
//					if (bodyLayout.getVisibility() == View.VISIBLE) {
//						bodyLayout.setVisibility(View.GONE);
//						entry.setSeleted(false);
//						currentEdit = null;
//					} else {
//						bodyLayout.setVisibility(View.VISIBLE);
//						entry.setSeleted(true);
//						currentEdit = (EditText) bodyLayout.getTag();
//						currentEdit.setFocusable(true);
//						currentEdit.setFocusableInTouchMode(true);
//						currentEdit.requestFocus();
//					}
//					preLayout = bodyLayout;
				}
			});
			
			holder.retweetView.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(context, NewsActivity.class);
					intent.putExtra(AppContext.NEWTYPE, 2);
					intent.putExtra("id", entry.getId());
					context.startActivity(intent);
				}
			});
			
			holder.photoView.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					byte[] tempBytes = null;
					try {
						String fileName = ServiceUtils.convertUrlToFileName(entry.getThumbnail_pic());
						String dir = ServiceUtils.getDirectory(fileName);
						String pathFileName = dir + "/" + fileName;
						File file = new File(pathFileName);
						FileInputStream fis = new FileInputStream(file);
						tempBytes = ServiceUtils.readStream(fis);
						fis.close();
						fis = null;
						file = null;
					} catch (Exception e) {
						e.printStackTrace();
					}
					Intent bigPicIntent = new Intent(context, PhotoDetailActivity.class);
					bigPicIntent.putExtra("pic_big", entry.getOriginal_pic());
					bigPicIntent.putExtra("thumbnail", tempBytes);
					context.startActivity(bigPicIntent);
				}
			});
			holder.commentButtonView.setTag(holder.editView);
			holder.commentButtonView.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					EditText editView = (EditText) v.getTag();
					String content = editView.getText().toString().trim();
					if (StringUtil.isBlank(content)) {
						((BasicActivity) context).onToast("评论内容不能为空!");
					} else {
						Object[] objs = new Object[3];
						objs[0] = content;
						objs[1] = entry.getId();
						objs[2] = isRetweet == true ? 1 : 0;
						UICore.eventTask(StatusTimeLineAdapter.this, (BasicActivity) context, comment_status, "", objs);
					}
				}
			});
			holder.retweetSelectLayout.setTag(holder.commentRetweetView);
			holder.retweetSelectLayout.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					ImageView retweetView = (ImageView) v.getTag();
					if (isRetweet) {
						isRetweet = false;
						retweetView.setBackgroundResource(R.drawable.btn_comment_sametime_unselect);
					} else {
						isRetweet = true;
						retweetView.setBackgroundResource(R.drawable.btn_comment_sametime_select);
					}
				}
			});
			holder.emotionView.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					if (!pop.isShowing()) {
						pop.showAtLocation(popViewToShow, Gravity.BOTTOM, 0, 0);
					} else {
						pop.dismiss();
					}
				}
			});
			
			/**转发*/
			if (entry.getRetweeted_status() != null) {
				holder.retweetLayout.setVisibility(View.VISIBLE);
				String username2 = entry.getRetweeted_status().getUser().getScreen_name() + ":" + "&nbsp;";
				holder.retweetTextView.setText(entry.getRetweeted_status().getText(), username2, AppContext.getInstance().getFaceMap());
				holder.retweetTimeView.setText(DateUtil.getCreateAt(entry.getRetweeted_status().getCreated_at()));
				if (StringUtil.isNotBlank(entry.getRetweeted_status().getThumbnail_pic())) {
					holder.retweetPhotoLayout.setVisibility(View.VISIBLE);
					photoLoader.DisplayImage(entry.getRetweeted_status().getThumbnail_pic(), holder.retweetPhotoView, R.drawable.nophoto);
				} else {
					holder.retweetPhotoLayout.setVisibility(View.GONE);
				}
				holder.retweetSourceView.setText(Html.fromHtml("来自" + entry.getRetweeted_status().getSource()));
				if (entry.getRetweeted_status().getReposts_count() > 0) {
					holder.retweetRetweetView.setText("转发(" + entry.getRetweeted_status().getReposts_count() + ")");
				} else {
					holder.retweetRetweetView.setText("转发");
				}
				if (entry.getRetweeted_status().getComments_count() > 0) {
					holder.retweetCommentView.setText("评论(" + entry.getRetweeted_status().getComments_count() + ")");
				} else {
					holder.retweetCommentView.setText("评论");
				}
				holder.retweetCommentView.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						if (entry.getRetweeted_status().getComments_count() > 0) {
							String choices[] = new String[] {"评论微博", "查看评论列表"};
							chooseAction(choices, entry.getRetweeted_status().getId());
						} else {
							Intent intent = new Intent(context, NewsActivity.class);
							intent.putExtra("id", entry.getRetweeted_status().getId());
							intent.putExtra(AppContext.NEWTYPE, 3);
							context.startActivity(intent);
						}
					}
				});
				holder.retweetRetweetView.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(context, NewsActivity.class);
						intent.putExtra(AppContext.NEWTYPE, 2);
						intent.putExtra("id", entry.getId());
						intent.putExtra("reid", entry.getRetweeted_status().getId());
						context.startActivity(intent);
					}
				});
				
				holder.retweetPhotoView.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						byte[] tempBytes = null;
						try {
							String fileName = ServiceUtils.convertUrlToFileName(entry.getRetweeted_status().getThumbnail_pic());
							String dir = ServiceUtils.getDirectory(fileName);
							String pathFileName = dir + "/" + fileName;
							File file = new File(pathFileName);
							FileInputStream fis = new FileInputStream(file);
							tempBytes = ServiceUtils.readStream(fis);
							fis.close();
							fis = null;
							file = null;
						} catch (Exception e) {
							e.printStackTrace();
						}
						Intent bigPicIntent = new Intent(context, PhotoDetailActivity.class);
						bigPicIntent.putExtra("pic_big", entry.getRetweeted_status().getOriginal_pic());
						bigPicIntent.putExtra("thumbnail", tempBytes);
						context.startActivity(bigPicIntent);
					}
				});
			} else {
				holder.retweetLayout.setVisibility(View.GONE);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return convertView;
	}


	@Override
	public void execute(int mes, Object obj) {
		try {
			switch (mes) {
			case comment_status:
				Object[] objs = (Object[]) obj;
				CommentEntry commentEntry = weibo.commentStatus(objs[0].toString(), objs[1].toString(), Integer.parseInt(objs[2].toString()));
				if (commentEntry != null) {
					handler.sendEmptyMessage(comment_status);
				} else {
					handler.sendEmptyMessage(comment_status_error);
				}
				break;
			case reply_comment:
				Object[] objs2 = (Object[]) obj;
				CommentEntry commentEntry2 = weibo.replayCommemnt(objs2[0].toString(), objs2[1].toString(), objs2[2].toString(),
						Integer.parseInt(objs2[3].toString()));
				if (commentEntry2 != null) {
					handler.sendEmptyMessage(reply_comment);
				} else {
					handler.sendEmptyMessage(comment_status_error);
				}
				break;
			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case comment_status_error:
			((BasicActivity) context).onToast("评论失败!");
			break;
		case comment_status:
			((BasicActivity) context).onToast("评论成功!");
			break;
		case reply_comment:
			((BasicActivity) context).onToast("回复评论成功!");
			break;
		default:
			break;
		}
		return false;
	}
	
	private void initGridView() {
		View view = LayoutInflater.from(context).inflate(R.layout.emotion_gridview, null);
		GridView gridView = (GridView) view.findViewById(R.id.emotion_gridview);
		GridViewAdapter gridAdapter = new GridViewAdapter(context);
		gridView.setAdapter(gridAdapter);
		pop = new PopupWindow(view, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, true);
		ColorDrawable dw = new ColorDrawable(-00000);
		pop.setBackgroundDrawable(dw);
		pop.update();
		gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				try {
					pop.dismiss();
					EmotionField filed = AppContext.getInstance().getEmotionFields().get(arg2);
					if (currentEdit != null) {
						currentEdit.append(filed.getPhrase());
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	private void chooseAction(String[] choices, final String id) {
		final Context dialogContext = new ContextThemeWrapper(context, android.R.style.Theme_Light);
	
		final ListAdapter adapter = new ArrayAdapter<String>(dialogContext,
				android.R.layout.simple_list_item_1, choices);

		final AlertDialog.Builder builder = new AlertDialog.Builder(
				dialogContext);
		builder.setTitle(R.string.system_info);
		builder.setSingleChoiceItems(adapter, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						if (which == 0) {
							Intent intent = new Intent(context, NewsActivity.class);
							intent.putExtra("id", id);
							intent.putExtra(AppContext.NEWTYPE, 3);
							context.startActivity(intent);
						} else {
							Intent intent = new Intent(context, CommentsActivity.class);
							intent.putExtra("id", id);
							context.startActivity(intent);
						}
					}
				});
		builder.create().show();
	}
}
